package com.minyifang.wcspf.work.ui.goods.activities;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseActivity;
import com.minyifang.wcspf.common.base.BaseMvpActivity;
import com.minyifang.wcspf.common.md5.SafeUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.common.utils.ToastUtils;
import com.minyifang.wcspf.work.MyApplication;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.goods.adapter.PicturesAdapter;
import com.minyifang.wcspf.work.ui.goods.model.ChoosePayTypeBean;
import com.minyifang.wcspf.work.ui.goods.model.WeChatPayBean;
import com.minyifang.wcspf.work.ui.goods.presenter.ChoosePayTypePresenter;
import com.minyifang.wcspf.work.ui.goods.view.ChoosePayTypeView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.rxjob.Job;


/**
 * 选择支付方式
 * Created by LuoYaWei on 2018/8/3.
 */
public class ChoosePayTypeActivity extends BaseMvpActivity<ChoosePayTypeView, ChoosePayTypePresenter> implements ChoosePayTypeView {


    public static final String BROADCAST_WECHAT_PAY = "wechat_pay";
    private static final String EXTRA_CONTENT = "content";

    private MyReceiver mReceiver;

    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.ll_pay_face)
    LinearLayout mLLFacePay;
    @BindView(R.id.ll_alipay)
    LinearLayout mLLAliPay;
    @BindView(R.id.ll_wechatpay)
    LinearLayout mLLWeChatPay;
    @BindView(R.id.ll_yuepay)
    LinearLayout mLLYuePay;
    @BindView(R.id.tv_balance)
    TextView mTvBalance;

    private String orderId;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, ChoosePayTypeActivity.class);
        intent.putExtra(EXTRA_CONTENT, orderId);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_choose_pay_type;
    }

    @Override
    protected void initView() {

        mReceiver = new MyReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(BROADCAST_WECHAT_PAY));

        Intent intent = getIntent();
        if (intent != null) {
            orderId = intent.getStringExtra(EXTRA_CONTENT);
        }
    }

    @Override
    protected void initData() {
        mPresenter.getData(orderId);
    }

    private int type;

    @OnClick(R.id.ll_alipay)
    void aliPay() {
        type = 1;
        pay(type);
    }

    @OnClick(R.id.ll_wechatpay)
    void weChatPay() {
        type = 2;
        pay(type);
    }

    @OnClick(R.id.ll_yuepay)
    void yuePay() {
        type = 3;
        pay(type);
    }

    @OnClick(R.id.ll_pay_face)
    void facePay() {
        type = 4;
        pay(type);
    }

    /**
     * 支付
     *
     * @param type 1，支付宝,2，微信3， 余额 4货到付款
     */
    private void pay(int type) {
        mPresenter.pay(orderId, type);
    }


    @Override
    protected ChoosePayTypePresenter createPresenter() {
        return new ChoosePayTypePresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

    /**
     * 支付页面数据的回调
     *
     * @param bean
     */
    @Override
    public void showPayInfo(ChoosePayTypeBean bean) {
        mTvPrice.setText(bean.getPayAmount());
        mTvBalance.setText(String.format("可用余额: %s", bean.getBalance()));
        //1，支付宝,2，微信3， 余额 4 货到付款
        mLLAliPay.setVisibility(bean.getPayStyle().contains("1") ? View.VISIBLE : View.GONE);
        mLLWeChatPay.setVisibility(bean.getPayStyle().contains("2") ? View.VISIBLE : View.GONE);
        mLLYuePay.setVisibility(bean.getPayStyle().contains("3") ? View.VISIBLE : View.GONE);
        mLLFacePay.setVisibility(bean.getPayStyle().contains("4") ? View.VISIBLE : View.GONE);

        orderId = bean.getOrderId();
    }

    /**
     * 发起支付的回调
     *
     * @param respond
     */
    @Override
    public void showPayRes(HttpRespond<String> respond) {

        switch (type) {
            case 1:
                final String orderInfo = SafeUtils.decrypt(respond.data);// 订单信息
                LogUtil.e("返回订单信息---" + orderInfo);
                Runnable payRunnable = () -> {
                    PayTask task = new PayTask(ChoosePayTypeActivity.this);
                    Map<String, String> result = task.payV2(orderInfo, true);

                    Message msg = new Message();
                    msg.what = ALI_PAY;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                };
                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
                break;

            case 2:
                LogUtil.e("" + SafeUtils.decrypt(respond.data));
                WeChatPayBean bean = new Gson().fromJson(SafeUtils.decrypt(respond.data), WeChatPayBean.class);
                IWXAPI api = WXAPIFactory.createWXAPI(this, bean.getAppid());
                api.registerApp(bean.getAppid());
                PayReq request = new PayReq();
                request.appId = bean.getAppid();
                request.partnerId = bean.getPartnerid();
                request.prepayId = bean.getPrepayid();
                request.packageValue = bean.getPackageX();
                request.nonceStr = bean.getNoncestr();
                request.timeStamp = bean.getTimestamp();
                request.sign = bean.getSign();
                api.sendReq(request);
                break;

            case 3:
            case 4:
                PayResultActivity.start(this, orderId);
                finish();
                break;
        }
    }

    @Override
    public void showPaySuccessRes(HttpRespond<String> respond) {
        PayResultActivity.start(ChoosePayTypeActivity.this, orderId);
        finish();
    }

    private static final int ALI_PAY = 0X12;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ALI_PAY:
                    Map<String, String> result = (Map<String, String>) msg.obj;
                    LogUtil.e("ali  -- " + result.toString());
                    if (result.containsKey("resultStatus")) {
                        if (result.get("resultStatus").equals("9000")) {
                            mPresenter.paySuccess(orderId, 1);
                        } else if (result.get("resultStatus").equals("8000")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showSucceed("正在处理中,请稍后查询");
                            finish();
                        } else if (result.get("resultStatus").equals("4000")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("订单支付失败");
                        } else if (result.get("resultStatus").equals("5000")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("订单重复请求");
                        } else if (result.get("resultStatus").equals("6001")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("用户中途取消");
                        } else if (result.get("resultStatus").equals("6002")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("网络连接出错");
                        } else if (result.get("resultStatus").equals("6004")) {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("支付结果未知，请稍后查询");
                            finish();
                        } else {
                            ToastHelper.getInstance(ChoosePayTypeActivity.this).showWarn("支付结果未知，请稍后查询");
                            finish();
                        }
                    }
                    break;
            }

        }
    };

    @Override
    public void showRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mPresenter.paySuccess(orderId, 2);
        }
    }
}
